import { createRouter, createWebHashHistory } from 'vue-router'
import { useStore } from '@/store'

// 定义路由元信息类型
declare module 'vue-router' {
  interface RouteMeta {
    requiresAuth: boolean
  }
}

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    // 登录页
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/platform/login/BaseLogin.vue'),
      meta: {
        requiresAuth: false
      }
    },
    // 匹配404
    {
      path: '/:pathMatch(.*)*',  // 使用Vue3新语法匹配所有路径
      redirect: '/404'
    },
    {
      path: '/',
      name: 'BaseLayout',
      component: () => import('@/views/platform/layout/BaseLayout.vue'),
      meta: {
        requiresAuth: true
      },
      redirect: '/home',
      children: [
        // 导航配置位置
        {
          path: '/home',
          name: 'HomePage',
          component: () => import('@/views/platform/Home.vue'),
          meta: {
            requiresAuth: true
          },
        },
        // 404页面
        {
          path: '/404',
          name: 'NotFound',
          component: () => import('@/views/platform/error/404.vue'),
          meta: {
            requiresAuth: false
          }
        },
        // 平台管理-导航管理
        {
          path: '/platform/navManage',
          name: 'navManage',
          component: () => import('@/views/platform/navManage/NavManage.vue'),
          meta: {
            requiresAuth: true
          }
        },

        
      ],
    }
  ]
})

// 处理登录状态
router.beforeEach((to, from, next) => {
  const store = useStore()
  const isAuthenticated = store.getters.isAuthenticated

  if (to.meta.requiresAuth && !isAuthenticated) {
    // 没有登录，重定向到登录页
    next('/login')
  } else if (!to.meta.requiresAuth && isAuthenticated && to.path === '/login') {
    // 已经登录，但是访问登录页，重定向到首页
  } else {
    // 其他情况，正常导航
    next()
  }
})

export default router
